package com.systemsetup.systemsetup.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.systemsetup.systemsetup.common.base.BaseService;
import com.systemsetup.systemsetup.model.Organization;
import com.systemsetup.systemsetup.model.User;
import com.systemsetup.systemsetup.support.model.RespEntity;
import com.systemsetup.systemsetup.support.mybatisplus.QueryWrapper;
import com.systemsetup.systemsetup.support.utils.requestutil.HttpRequestUtil;
import com.systemsetup.systemsetup.web.mapper.BusinessMapper;
import com.systemsetup.systemsetup.web.mapper.OrganizationMapper;
import com.systemsetup.systemsetup.web.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * @author Yang
 */
@Service
@Slf4j
public class OrganizationTreeListService extends BaseService {

    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BusinessMapper businessMapper;

    /**
     * 机构树形菜单服务
     *
     * @param jsonParam
     * @return
     */
    public RespEntity orgTreeList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        Organization myOrganization = organizationMapper.selectById(homeId);
        List<Organization> orgs = getOrganizations(homeId);
        myOrganization.put("orgs", orgs);
        return RespEntity.success(myOrganization);
    }

    public List<Organization> getOrganizations(String id) {
        List<Organization> list = new ArrayList<>();
        List<Organization> oneList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", id));
        for (Organization one : oneList) {
            List<Organization> twoList = getOrganizations(one.getId());
            one.put("orgs", twoList);
            list.add(one);
        }
        return list;
    }


    public List<Organization> list(String pid) {

        List<Organization> oneList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", "0"));
        for (Organization one : oneList) {
            List<Organization> twoList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", one.getId()));
            for (Organization two : twoList) {
                List<Organization> threeList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", two.getId()));
                for (Organization three : threeList) {
                    List<Organization> fourList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", three.getId()));
                    three.put("orgs", fourList);
                }
                two.put("orgs", threeList);
            }
            one.put("orgs", twoList);
        }
        return oneList;
    }

    /**
     * 机构删除
     *
     * @param jsonParam
     * @return
     */
    public RespEntity orgDelete(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String id = jsonParam.getStr("id");
        //自己不能删除自己
        if (homeId.equals(id)) {
            return RespEntity.fail("没有权限删除!");
        }
        if (StrUtil.isBlank(id)) return RespEntity.fail("机构id不能为空");
        //验证时候有子机构
        List<Organization> organizationList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", id));
        if (!organizationList.isEmpty()) return RespEntity.fail("有子机构，不能删除");
        //rest请求单位模块的单位不分页列表接口，验证是否有下属单位
        jsonParam.put("orgId", id);
        com.alibaba.fastjson.JSONObject jsons = makeDataForToken(jsonParam, "businessJava", "config", "businessListCount", "business");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        int count = jsons.getInteger("count");
        if (count > 0) return RespEntity.fail("有下属单位，不能删除");
        //验证机构下是否有用户
        List<User> userList = userMapper.selectList(new QueryWrapper<User>().eq("home_id", id));
        if (!userList.isEmpty()) return RespEntity.fail("机构下有用户，不能删除");
        Organization organization = organizationMapper.selectById(id);
        jsonParam.put("homeId", id);
        jsonParam.put("pid", organization.getPid());
        makeDataForToken(jsonParam, "communicationJava", "config", "releaseNumberPieces", "communication");
        //删除机构
        organizationMapper.deleteById(id);
        return RespEntity.success();
    }

    /**
     * 机构新增
     *
     * @param jsonParam
     * @return
     */
    public RespEntity orgAdd(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String pid = jsonParam.getStr("pid");
        String name = jsonParam.getStr("name");
        //新增机构
        String id = UUID.randomUUID().toString();
        Organization organization = new Organization();
        organization.setName(name);
        organization.setPid(pid);
        organization.setId(id);
        organization.setReginid(jsonParam.getStr("reginId"));
        if (pid.equals("0")) {
            organization.setAllId(id);
        } else {
            String orgIds = getOrganizationss("", pid);
            organization.setAllId(orgIds + "," + id);
        }
        if (jsonParam.containsKey("des")) organization.setDes(jsonParam.getStr("des"));
        organizationMapper.insert(organization);
        return RespEntity.success();
    }

    /**
     * 机构修改
     *
     * @param jsonParam
     * @return
     */
    public RespEntity orgUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String id = jsonParam.getStr("id");
        String name = jsonParam.getStr("name");
        //新增机构
        Organization organization = new Organization();
        organization.setName(name);
        organization.setId(id);
        organization.setReginid(jsonParam.getStr("reginId"));
        if (jsonParam.containsKey("des")) organization.setDes(jsonParam.getStr("des"));
        organizationMapper.updateById(organization);
        return RespEntity.success();
    }

    /**
     * 机构详情
     *
     * @param jsonParam
     * @return
     */
    public RespEntity orgDetail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String id = jsonParam.getStr("id");
        String name = jsonParam.getStr("name");
        //新增机构
        Organization organization = organizationMapper.selectById(jsonParam.getStr("id"));
        if (organization == null) {
            return RespEntity.fail("机构id错误");
        }
        if (!organization.getPid().equals("0")) {
            Organization organizationP = organizationMapper.selectById(organization.getPid());
            organization.put("pName", organizationP.getName());
        } else {
            organization.put("pName", "");
        }
        return RespEntity.success(organization);
    }

    /**
     * 机构列表
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getOrgList(JSONObject jsonParam) {

        List<Organization> organizationList = organizationMapper.getOrgList();

        return RespEntity.success(organizationList);
    }

    /**
     * @Author YangYu
     * @Description 根据pid查询机构列表
     * @Date Created in 13:28 2023/6/2
     * @Param [jsonParam]
     */

    public RespEntity getPidOrgList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String id = jsonParam.getStr("id");
        String name = jsonParam.getStr("name");
        List<Organization> organizationList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", jsonParam.getStr("pid")));
        return RespEntity.success(organizationList);
    }

    /**
     * @param jsonParam
     * @return
     */
    public Map<String, Object> getAllOrgIdList(Map<String, Object> jsonParam) {
        //返回数据
        Map<String, Object> map = new HashMap<>();
        //查询机构列表
        List<Organization> organizationList = organizationMapper.selectList(new QueryWrapper<Organization>());
        for (Organization org : organizationList) {
            map.put(org.getId(), org.getAllId());
        }
        return map;
    }

    public static void main(String[] args) {
        String n = "3f800000";
        Long ll = Long.parseLong(n, 16);
        Float ff = Float.intBitsToFloat(ll.intValue());
        System.out.println(ff);
    }

    /**
     * 查询所有的机构Id
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getOrganizationsId(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        //获取所有单位的id
        List<Organization> organizationsIdList = organizationMapper.getOrganizationsId();
        List<String> organizationsList = new ArrayList<>();
        for (Organization organization : organizationsIdList) {
            organizationsList.add(organization.getId());
        }
        return RespEntity.success(organizationsList.toString());
    }

    /**
     * 导入时用的机构id
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getOrganizationListId(JSONObject jsonParam) {
        List<Organization> regionList = organizationMapper.getOrgListId();
        return RespEntity.success(regionList);
    }

    /**
     * 根据机构id查询所有的父id
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getorgAllListId(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = "";
        if (jsonParam.containsKey("homeId")) {
            homeId = jsonParam.getStr("homeId");
        } else {
            homeId = token.getString("home_id");
        }
        JSONObject jsonObject = new JSONObject();
        //String orgIds = getOrganizationss("", homeId);
        Organization organization = organizationMapper.selectById(homeId);
        jsonObject.put("orgIds", organization.getAllId());
        return RespEntity.success(jsonObject);
    }

    /**
     * 根据机构id查询所有的父id(不带Token)
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getOrgAllId(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String homeId = jsonParam.getStr("homeId");
        JSONObject jsonObject = new JSONObject();
        String orgIds = getOrganizationss("", homeId);
        jsonObject.put("orgIds", orgIds);
        return RespEntity.success(jsonObject);
    }

    public String getOrganizationss(String ids, String id) {
        Organization one = organizationMapper.selectById(id);
        ids = one.getId() + "," + ids;
        if (!one.getPid().equals("0")) {
            ids = getOrganizationss(ids, one.getPid());
        } else {
            ids = ids.substring(0, ids.length() - 1);
        }
        return ids;
    }

    /**
     * 获取本机及下级的机构id
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getOrgIdAndDownOrgIds(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String orgIds = getOrganizationIds(homeId, homeId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orgIds", orgIds);
        return RespEntity.success(jsonObject);
    }

    public String getOrganizationIds(String ids, String id) {
        List<Organization> oneList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", id));
        if (!oneList.isEmpty()) {
            for (Organization one : oneList) {
                ids = one.getId() + "," + ids;
            }
            for (Organization one : oneList) {
                ids = getOrganizationIds(ids, one.getId());
            }
        }
        return ids;
    }

    public RespEntity washData(JSONObject jsonParam) {
        List<Organization> list = organizationMapper.selectList(new QueryWrapper<>());
        for (Organization organization : list) {
            //新增机构
            String orgIds = getOrganizationss("", organization.getId());
            organization.setAllId(orgIds);
            organization.setId(organization.getId());
            organizationMapper.updateById(organization);
        }
        return RespEntity.success();

    }

}
